package com.chen.common.sftp.handler;

import cn.hutool.core.util.StrUtil;
import com.chen.common.sftp.factory.ChannelSftpFactory;
import com.chen.common.sftp.properties.SftpPoolProperties;
import com.jcraft.jsch.ChannelSftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author tuxingzhou
 * @Title: SFTPPoolServiceImpl
 * @Package
 * @Description:
 * @date 2023/10/1216:02
 */
@Slf4j
@Component
public class SftpPoolHandler {

    /**
     * ftp 连接池生成
     */
    private GenericObjectPool<ChannelSftp> pool;

    /**
     * ftp 客户端配置文件
     */
    @Resource
    private SftpPoolProperties config;

    /**
     * ftp 客户端工厂
     */
    @Resource
    private ChannelSftpFactory factory;

    /**
     * 初始化pool
     */
    @PostConstruct
    public void initPool() {
        if(StrUtil.isBlank(this.config.getHost())){
            log.info("初始化SFTP失败，请FTP的Host为空，则不进行初始化！");
            return;
        }
        this.pool = new GenericObjectPool<ChannelSftp>(factory, this.config);
    }

    /**
     * 获取sftp
     */
    public ChannelSftp borrowObject() {
        if (this.pool != null) {
            try {
                return this.pool.borrowObject();
            } catch (Exception e) {
                log.error("获取 ChannelSftp 失败 -> {}", e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 归还 sftp
     */
    public void returnObject(ChannelSftp channelSftp) {
        if (this.pool != null && channelSftp != null) {
            this.pool.returnObject(channelSftp);
        }
    }

    public SftpPoolProperties getFtpPoolConfig() {
        return config;
    }
}
